package com.trimps.steps.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ModelAttribute;

import com.hotfire.template.common.Constants;
import com.hotfire.template.common.HttpSevletRequstContextHolder;
import com.trimps.steps.pojo.User;

public class BaseController {
    public HttpServletRequest  request;
    public HttpServletResponse response;

    @ModelAttribute
    public void getRequestResponse(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    protected Map<String, Object> buildSuccessMsg(String msg) {
        return buildMsg(msg, true, new HashMap<String, Object>());
    }

    protected Map<String, Object> buildSuccessMsg(String msg, Map<String, Object> map) {
        return buildMsg(msg, true, map);
    }

    protected Map<String, Object> buildFailureMsg(String msg) {
        return buildMsg(msg, false, new HashMap<String, Object>());
    }

    protected Map<String, Object> buildFailureMsg(String msg, Map<String, Object> map) {
        return buildMsg(msg, false, map);
    }

    private Map<String, Object> buildMsg(String msg, boolean status, Map<String, Object> map) {
        map.put("status", status);
        map.put("msg", msg);
        return map;
    }

    public String sendErrorPage(HttpServletRequest request, String why) {
        request.setAttribute("why", why);
        return "/error";
    }

    public User getUser() {
        HttpServletRequest requst = HttpSevletRequstContextHolder.getServletRequest();
        if (requst != null) {
            return (User) requst.getSession().getAttribute(Constants.USER_SESSION_ATTR);
        }
        return null;
    }

    public Integer getUserId() {
        User user = getUser();
        if(user != null){
            return user.getId();
        }
        return null;
    }

}
